package cc.telecomdigital.tdstock.trading;

import com.lightstreamer.ls_client.UpdateInfo;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Application_Framework.LS_ItemRequestType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class Trade_StockInputActivity extends Trade_TemplateActivity implements
	OnClickListener, ILS_UserClient_Response
{
	private View.OnClickListener	keyboardListener;

	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		setContentView(R.layout.stocktrade);

		TextView textViewObj = (TextView) findViewById(R.id.view_acctheader_Title);
		if (TradeAppInfo.IsDemoAccount())
			textViewObj.setText(TradeAppInfo.GetUserName());
		else
			textViewObj.setText(R.string.stockTradeText);

		ImageButton imgButton;

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Refresh);
		imgButton.setVisibility(View.INVISIBLE);

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Home);
		imgButton.setOnClickListener(this);

		// Where it store the numeric stock code
		((TextView) findViewById(R.id.stocktrade_StockCode)).setText("");

		// Prompt Keyboard on first start
		keyboardListener = new View.OnClickListener()
		{
			// Support a maximum of 5 characters
			@Override
			public void onClick(View iViewObj)
			{
				int objId;
				TextView textViewObj;
				String tmpString;

				objId = iViewObj.getId();

				textViewObj = (TextView) findViewById(R.id.stocktrade_StockCode);
				tmpString = textViewObj.getText().toString();
				if ((tmpString == null) || (tmpString.length() == 0))
					tmpString = "";

				if (tmpString.length() >= Trade_AppConstant.maxStockCodeEntry)
				{
					if (objId != R.id.view_stocktrade_num_keypad_Back)
						return;
				}

				switch (objId)
				{
					case R.id.view_stocktrade_num_keypad_0:
						tmpString += "0";
						break;
					case R.id.view_stocktrade_num_keypad_1:
						tmpString += "1";
						break;
					case R.id.view_stocktrade_num_keypad_2:
						tmpString += "2";
						break;
					case R.id.view_stocktrade_num_keypad_3:
						tmpString += "3";
						break;
					case R.id.view_stocktrade_num_keypad_4:
						tmpString += "4";
						break;
					case R.id.view_stocktrade_num_keypad_5:
						tmpString += "5";
						break;
					case R.id.view_stocktrade_num_keypad_6:
						tmpString += "6";
						break;
					case R.id.view_stocktrade_num_keypad_7:
						tmpString += "7";
						break;
					case R.id.view_stocktrade_num_keypad_8:
						tmpString += "8";
						break;
					case R.id.view_stocktrade_num_keypad_9:
						tmpString += "9";
						break;
					case R.id.view_stocktrade_num_keypad_Back:
						if (tmpString.length() != 0)
							tmpString = tmpString.substring(0,
									tmpString.length() - 1);
						break;
				}
				textViewObj.setText(tmpString);
			}
		};

		// Map the key
		((Button) findViewById(R.id.view_stocktrade_num_keypad_0))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_1))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_2))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_3))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_4))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_5))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_6))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_7))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_8))
				.setOnClickListener(keyboardListener);
		((Button) findViewById(R.id.view_stocktrade_num_keypad_9))
				.setOnClickListener(keyboardListener);
		((ImageButton) findViewById(R.id.view_stocktrade_num_keypad_Back))
				.setOnClickListener(keyboardListener);
		((ImageButton) findViewById(R.id.view_stocktrade_num_keypad_Enter))
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						//Prevent multiple click, which kill multiple request
						if (IsNetworkAvailable() == false)
						{
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}					
						
						v.setClickable(false);
						// When an OK is pressed, we will start the keypad
						// with available information
						String tmpString;

						tmpString = ((TextView) findViewById(R.id.stocktrade_StockCode))
								.getText().toString();
								
						if ((tmpString == null)
								|| (tmpString.length() == 0) || tmpString.equals("0"))
						{
							ShowPromptMessage(getString(R.string.inputEntryErrorText));
							v.setClickable(true);							
							return;
						}

						tmpString = Trade_StockFunctionTools.RemoveStockCodeFormat(tmpString);						

						ObtainStockQuote(tmpString);
						v.setClickable(true);						
					}						
				});
	}

	private final String[] reqSchema = {"StockChiShortName", "ErrorMessage", "LotSize",	
								 "Net", "NetPercentage", "Nominal",				
								 "BidPrice","AskPrice", "CurrencyCode"};
	/** Enter from a UI Thread to request a non-null stock code **/
	private void ObtainStockQuote(String iStockCode)
	{
		ShowWaitingDialog();

		requestCode = Trade_StockFunctionTools.FormatFullStockCode(iStockCode);
		/* If we are using demo account, a pretend of network request happen to retrieve
		 * our demo data, the downloadMethod is for us to use if desire */
		if (TradeAppInfo.IsDemoAccount() || TradeAppInfo.IsBMPMode())
		{
			final TradeGetDetailStockQuote quoteRequest;
	
		    quoteRequest = new TradeGetDetailStockQuote( actContext);
			quoteRequest.SetRequestQuoteInfo( appHost.IsDevelopment(), requestCode, appHost.GetLSClient_AccountLogonName(), appHost.GetLSClient_SessionKey());
			quoteRequest.SendRequest( TradeAppInfo.IsDemoAccount(),
					new ITradeGetStockQuoteResponse()
					{
						@Override
						public void ResponseFunc( boolean iSuccessfulSend, TradeGetStockQuoteResult iResponse)
						{
							quoteRequest.Dispose();
							if (iSuccessfulSend == false)
							{
								ShowPromptMessage(getString(R.string.commErrorText));
								return;
							}
	
							if (!iResponse.resultCode.equals("0"))
							{
								String textValue;
								
								textValue = iResponse.errorMessage;
								if (textValue.equals(""))
									textValue = getString(R.string.commErrorText);
								ShowPromptMessage(textValue);
								//-1 is for Session Expired, we better subscribe the key again
								if (iResponse.resultCode.equals("-1"))
									appHost.LS_Client_ResetConnection();							
								return;
							}
							
							// The process takes too long
							// on UI, we create this to
							// blind the user
							// DismissWaitingDialog();
							EnterToKeyPad(iResponse.stockQuoteItem);
							// Fool UI Method
							DismissWaitingDialog_Background();
						}
					});
			return;
		}

		if (TradeAppInfo.HasSessionTimeExpired())
		{
			ShowTimeExpiredBox();
			return;
		}	
		
		if (IsNetworkAvailable() == false)
		{
			ShowPromptMessage(getString(R.string.commErrorText));
			return;
		}
		
		//Now we are using light streamer		
		LS_SubscriptionItem quoteItem;
		
		quoteItem = new LS_SubscriptionItem("TELETEXT");
		// We should not use something with leading zero value */
		quoteItem.AddSubscribeItem(iStockCode);
		quoteItem.SetSubscribeSchema(reqSchema);
		
		if (lightStreamerID == null)
			lightStreamerID = LSGetUniqueID();
		
		if (LightStreamerSubscribeItem(lightStreamerID, quoteItem, LS_ItemRequestType.NONE, this) == false)
		{		
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}
		
		//Hold a error message after the delay time, 8 seconds
		UIHandler.postDelayed(lightStreamerErrorPrompt, Trade_AppConstant.lightStreamerWaitTime);
	}
		
	@Override
	public void onPause()
	{		
		super.onPause();
//		((TextView) findViewById(R.id.stocktrade_StockCode)).setText("");		
		LightStreamerTimeoutTaskCancel();
	}
	
	private String    lightStreamerID = null;
	private void LightStreamerTimeoutTaskCancel()
	{
		UIHandler.removeCallbacks(lightStreamerErrorPrompt);		
	}
	
	private Runnable lightStreamerErrorPrompt = new Runnable()
	{
		public void run()
		{
			if (lightStreamerID == null)
				return;
			
			LightStreamerUnsubscribeItem(lightStreamerID);			
			if (debugMode)
				TDStockLog.i(GetIdentity(), "The LightStreamer(" + lightStreamerID + ")" + "requests timeout.");

			lightStreamerID = null;
			ShowPromptMessage(getString(R.string.commErrorText));	
		}
	};
	
	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}

	private String  requestCode = null;
	private Handler UIHandler = new Handler();
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
		String tmpValue;

		tmpValue = iUpdateInfo.getNewValue("ErrorMessage");
		//Then we can prompt the error
		if ((tmpValue != null) && (tmpValue.length() > 0))
		{
			final String displayText;
			
			//Cancel our timeout task
			LightStreamerTimeoutTaskCancel();			
			if (tmpValue.equals(TradeAppInfo.stockNotFoundText))
				displayText = getString(R.string.StockNotFound_Text);
			else
				displayText = tmpValue;
			Runnable uiAcccess = new Runnable()
			{
				public void run()
				{
					ShowPromptMessage(displayText);
				}
			};					
			UIHandler.post(uiAcccess);
			LightStreamerUnsubscribeItem(iIdentifier);
			lightStreamerID = null;
			requestCode = null;
			return;
		}

		//Not check for valid date
		tmpValue = iUpdateInfo.getNewValue("StockChiShortName");
		//We consider this is a false value
		if ((tmpValue == null) || (tmpValue.length() == 0))
			return;
		
		//Cancel our timeout task
		LightStreamerTimeoutTaskCancel();		
		
		String 			    tmpValue2, tmpValue3;
		Trade_StockViewInfoItem stockItem;
		
		stockItem = new Trade_StockViewInfoItem(requestCode, tmpValue, null);
		tmpValue = iUpdateInfo.getNewValue("Nominal");
		tmpValue2 = iUpdateInfo.getNewValue("BidPrice");
		tmpValue3 = iUpdateInfo.getNewValue("AskPrice");	
		stockItem.SetPriceInfo(tmpValue, tmpValue2, tmpValue3, false);
		
		tmpValue = iUpdateInfo.getNewValue("Net");
		tmpValue2 = iUpdateInfo.getNewValue("NetPercentage");
		stockItem.SetNetDiffPrice(tmpValue, tmpValue2);
		
		tmpValue = iUpdateInfo.getNewValue("LotSize");
		stockItem.SetStepVolume(tmpValue);
				
		tmpValue = iUpdateInfo.getNewValue("CurrencyCode");
		stockItem.SetCurrencyCode(tmpValue);
		
		//Calculate the spread price
		tmpValue = Trade_StockFunctionTools.GetStockPriceSpread(stockItem.GetCurPriceText());
		stockItem.SetSpreadPrice(tmpValue);
					
		//Expecting the onPause to help
//		LightStreamerUnsubscribeItem(iIdentifier);
		lightStreamerID = null;
		requestCode     = null;		
		
		if (debugMode)
			TDStockLog.i(GetIdentity(), stockItem.toString());
		//We have the info and we could switch
		//Ready to Switch
		EnterToKeyPad(stockItem);
		// Fool UI Method
		DismissWaitingDialog_Background();				
	}

	@Override
	public void LS_UserClient_ConnectionReport( CONNECTION_STATUS iStatus)
	{	
		if (TradeAppInfo.IsDemoAccount() || TradeAppInfo.IsBMPMode())
			return;
				
		if ((iStatus != CONNECTION_STATUS.CONNECTED) && (requestCode != null))
		{
			DismissWaitingDialog();
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			if (lightStreamerID != null)
			{
				LightStreamerUnsubscribeItem(lightStreamerID);
				lightStreamerID = null;
			}
			return;
		}		
		
	}

	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{	}			
	
	private void EnterToKeyPad(Trade_StockViewInfoItem iInfoItem)
	{
		// When an OK is pressed, we will start the keypad with available
		// information
		Intent intentObj;
		Trade_StockReqOrderItem transferObj;

		intentObj = new Intent(actContext, Trade_OrderKeypadActivity.class);
		if (TradeAppInfo.IsDemoAccount())
		{
			transferObj = new Trade_StockReqOrderItem("1234", iInfoItem.stockCode, iInfoItem.chnName,
					iInfoItem.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("0", "0", "400");
			// Use previous price for setting
			transferObj.SetOrderPrice("882.5");
			transferObj.SetCurrencyCode(TradeAppInfo.HKDCode);
		}
		else
		{
			// Provide with no order no
			transferObj = new Trade_StockReqOrderItem("",
					iInfoItem.stockCode, iInfoItem.chnName,
					iInfoItem.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("0", "0", iInfoItem.stepVolume);
			// Use previous price for setting
			transferObj.SetOrderPrice(iInfoItem.GetCurAskPriceText());
			transferObj.SetCurrencyCode(iInfoItem.currencyCode);			
		}
		transferObj.SetOrderType("E");
		// Assume it is a buy
		transferObj.SetOrderSide(Trade_StockReqOrderItem.TRANSACTIONTYPE_BID);

		//Place the Order info, then the Stock View Info
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo,
				transferObj);
		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iInfoItem);
		
		// Place the bundle object to the intent
		SwitchForwardActivity(Trade_OrderKeypadActivity.class, intentObj);
	}

	@Override
	public void onClick(View iViewObj)
	{
		int iObjId;

		iObjId = iViewObj.getId();
		switch (iObjId)
		{
			case R.id.view_acctheader_Home:
				SwitchFreeActivity(Trade_tradingOptionActivity.class);
				break;
		}
	}
}
